package com.zr.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zr.model.User;
import com.zr.service.UserService;
import com.zr.service.impl.UserServicImpl;

import net.sf.json.JSONObject;
 
public class LoginAction extends HttpServlet{
		UserService  us =new UserServicImpl();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	
//接收到页面发送的表单，里面的名字
		String  uname         =req.getParameter("username");
		String  upasw         =req.getParameter("password");
		String  client_token  =req.getParameter("Reqtoken");
		
		String  server_token  =(String) req.getSession().getAttribute("token");		
		//是接受的字符串的参数变量
		//判断页面的  参数接收到了没有
		HttpSession session = req.getSession();
		session.setAttribute("uname",uname);
		session.setAttribute("upasw",upasw);

		
		JSONObject  j =new JSONObject();
		resp.setCharacterEncoding("utf8");
		PrintWriter pw =resp.getWriter();
		 
		User  user=us.getUserService(uname, upasw);
	    if(user.getUname()!=null){	
		   if(server_token.equals(client_token)){
			  
			    j.put("s", true);
				pw.write(j.toString());
				session.removeAttribute("token");
		
		   }else{
			   req.getRequestDispatcher("/token").forward(req, resp);	
		   }
						   
	   }else{		   
		   j.put("s", false);
		   j.put("msg","账户名或密码错误");
		   pw.write(j.toString());		   
	   }
	  
	   
	}
}
